package com.badibadi.mytools;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import net.tsz.afinal.FinalHttp;
import net.tsz.afinal.http.AjaxCallBack;

import com.badibadi.infos.ApkInfos;
import com.badibadi.infos.Results;
import com.badibadi.uniclubber.R;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnClickListener;
import android.content.pm.PackageManager.NameNotFoundException;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.Toast;

public class SoundUtils {
	private static final String TAG = "SoundUtils";
	/* 下载中 */
	private static final int DOWNLOAD = 1;
	/* 下载结束 */
	private static final int DOWNLOAD_FINISH = 2;
	/* 保存解析的XML信息 */
	HashMap<String, String> mHashMap;

	/* 记录进度条数量 */
	private int progress;
	/* 是否取消更新 */
	private boolean cancelUpdate = false;

	private Context mContext;
	// /* 更新进度条 */
	// private ProgressBar mProgress;
	private Dialog mDownloadDialog;
	private Results results;
	private ApkInfos apkInfos;

	// private String

	/* 下载保存路径 */
	private String mSavePath;
	// 语音操作对象
	private MediaPlayer mPlayer = null;
	private String downPath;// 下载路径

	private Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			// 正在下载
			case DOWNLOAD:
				// 设置进度条位置
				// mProgress.setProgress(progress);
				try {
					Utils.setProgress_hen(msg.getData().getInt("msg"));
				} catch (Exception e) {
					// TODO: handle exception
				}
				break;
			case DOWNLOAD_FINISH:// 播放
//				   

				try {
					Utils.ExitProgress_hen(mContext);
					String msString = msg.getData().getString("msg");

					File file = new File(msString);
					if (file.exists()) {
						startPlay(msString);
//						   
					}
				} catch (Exception e) {
					// TODO: handle exception
				}

				// 安装文件
				// installApk();
				break;
			case 3:
				// Utils.ExitPrgress(mContext);
				Utils.showMessage(mContext,
						mContext.getResources().getString(R.string.l_net_error));
				break;
			case 5:
				// Utils.ExitPrgress(mContext);
				Utils.showMessage(mContext,
						mContext.getResources().getString(R.string.l_xa10));
				break;
			default:
				break;
			}
		};
	};

	public SoundUtils(Context context) {
		this.mContext = context;

	}

	/**
	 * 显示软件更新对话框
	 */
	private void showNoticeDialog() {
		// 构造对话框
		AlertDialog.Builder builder = new Builder(mContext);
		builder.setTitle(R.string.soft_update_title);
		builder.setMessage(R.string.soft_update_info);
		// 更新
		builder.setPositiveButton(R.string.soft_update_updatebtn,
				new OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
						// 显示下载对话框
						showDownloadDialog();
					}
				});
		// 稍后更新
		builder.setNegativeButton(R.string.soft_update_later,
				new OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
					}
				});
		Dialog noticeDialog = builder.create();
		noticeDialog.show();
	}

	/**
	 * 显示软件下载对话框
	 */
	private void showDownloadDialog() {
		// 构造软件下载对话框
		AlertDialog.Builder builder = new Builder(mContext);
		builder.setTitle(R.string.soft_updating);
		// 给下载对话框增加进度条
		final LayoutInflater inflater = LayoutInflater.from(mContext);
		View v = inflater.inflate(R.layout.softupdate_progress, null);
		// mProgress = (ProgressBar) v.findViewById(R.id.update_progress);
		builder.setView(v);
		// 取消更新
		builder.setNegativeButton(R.string.soft_update_cancel,
				new OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
						// 设置取消状态
						cancelUpdate = true;
					}
				});
		mDownloadDialog = builder.create();
		mDownloadDialog.show();
		// 现在文件
		// downloadSound();
	}

	/**
	 * 下载录音
	 */
	public void downloadSound(String path) {

		if (mPlayer != null) {
			stopPlay();
		} else {
			downPath = Constants.YuyingDownLoad + path; 
			mSavePath = IOUtils.getSaveObjectPath(mContext, MD5.getMD5(downPath));
			// 启动新线程下载软件
			// new downloadApkThread().start();
			downloadSound();
		}
	}

	private void downloadSound() {
		Utils.showProgress_hen(mContext);
		FinalHttp fh = new FinalHttp();
		fh.download(downPath, mSavePath, new AjaxCallBack<File>() {
			@Override
			public void onLoading(long count, long current) {
				// TODO Auto-generated method stub
				super.onLoading(count, current);
				Message msg = new Message();
				Bundle bun = new Bundle();
				msg.what = DOWNLOAD;
				bun.putInt("msg", (int) count);
				msg.setData(bun);
				mHandler.sendMessage(msg);

			}

			@Override
			public void onStart() {
				// TODO Auto-generated method stub
				super.onStart();
			}

			@Override
			public void onSuccess(File t) {
				// TODO Auto-generated method stub
				super.onSuccess(t);
				if (t.exists()) {
					Message msg = new Message();
					Bundle bun = new Bundle();
					msg.what = DOWNLOAD_FINISH;
					bun.putString("msg", t.getPath());
					msg.setData(bun);
					mHandler.sendMessage(msg);
				}

			}

			@Override
			public void onFailure(Throwable t, int errorNo, String strMsg) {
				// TODO Auto-generated method stub
				super.onFailure(t, errorNo, strMsg);
			}
		});
	}

	// /**
	// * 下载文件线程
	// */
	// private class downloadApkThread extends Thread {
	//
	//
	// @Override
	// public void run() {
	// try {
	// // 判断SD卡是否存在，并且是否具有读写权限
	// if (Environment.getExternalStorageState().equals(
	// Environment.MEDIA_MOUNTED)) {
	// // 获得存储卡的路径
	// // String sdpath = IOUtils.getSaveObjectPath(mContext, TAG);
	// // mSavePath = sdpath + "download";
	// URL url = new URL(mSavePath);
	// // 创建连接
	// HttpURLConnection conn = (HttpURLConnection) url
	// .openConnection();
	// conn.connect();
	// // 获取文件大小
	// int length = conn.getContentLength();
	// // 创建输入流
	// InputStream is = conn.getInputStream();
	//
	// File file = new File(mSavePath);
	// // 判断文件目录是否存在
	// if (!file.exists()) {
	// file.mkdir();
	// }
	// File apkFile = new File(mSavePath,
	// apkInfos.getApkFileName());
	// FileOutputStream fos = new FileOutputStream(apkFile);
	// int count = 0;
	// // 缓存
	// byte buf[] = new byte[1024];
	// // 写入到文件中
	// do {
	// int numread = is.read(buf);
	// count += numread;
	// // 计算进度条位置
	// progress = (int) (((float) count / length) * 100);
	// // 更新进度
	// mHandler.sendEmptyMessage(DOWNLOAD);
	// if (numread <= 0) {
	// // 下载完成
	// mHandler.sendEmptyMessage(DOWNLOAD_FINISH);
	// break;
	// }
	// // 写入文件
	// fos.write(buf, 0, numread);
	// } while (!cancelUpdate);// 点击取消就停止下载.
	// fos.close();
	// is.close();
	// }
	// } catch (MalformedURLException e) {
	//    
	// } catch (IOException e) {
	//    
	// }
	// // 取消下载对话框显示
	// mDownloadDialog.dismiss();
	// }
	// };

	// 开始播放
	public void startPlay(String path) {
		stopPlay();
		mPlayer = new MediaPlayer();
		try {
			mPlayer.setDataSource(path);
//			mPlayer.getDuration()()()
			mPlayer.prepare();
			mPlayer.start();
		} catch (IOException e) {
//			   
		}
	}
/**
 * 获取持续时间
 * @param path
 * @return
 */
	public int getDuration(String path)
	{
		mPlayer=new MediaPlayer();
		try {
//			   ("path="+path);
//			   
			mPlayer.setDataSource(path);
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			   
		} catch (SecurityException e) {
			// TODO Auto-generated catch block
			   
		} catch (IllegalStateException e) {
			// TODO Auto-generated catch block
			   
		} catch (IOException e) {
			// TODO Auto-generated catch block
			   
		}
		int b=mPlayer.getVideoWidth();
//		   
		return b;
	}
	
	// 停止播放
	public void stopPlay() {
		if (mPlayer != null) {
			mPlayer.release();
			mPlayer = null;
		}

	}

	// /**
	// * 安装APK文件
	// */
	// private void installApk() {
	// File apkfile = new File(mSavePath, apkInfos.getApkFileName());
	// if (!apkfile.exists()) {
	// return;
	// }
	// // 通过Intent安装APK文件
	// Intent i = new Intent(Intent.ACTION_VIEW);
	// i.setDataAndType(Uri.parse("file://" + apkfile.toString()),
	// "application/vnd.android.package-archive");
	// mContext.startActivity(i);
	// }
}
